package gsw.tool.skin;

import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import gsw.tool.skin.utils.SkinThemeUtils;


/**
 * Created by siwei on 2018/3/18.
 */

/**
 * View的属性集合
 */
class SkinAttribute {
    //自定义字体属性
    public final static String SKINTYPEFACE = "skinTypeface";
    //字体
    private Typeface typeface;
    private static final List<String> attributes = new ArrayList<>();
    List<SkinView> skinViews = new ArrayList<>();


    static {
        attributes.add("background");
        attributes.add("src");

        attributes.add("textColor");
        attributes.add("drawableLeft");
        attributes.add("drawableTop");
        attributes.add("drawableRight");
        attributes.add("drawableBottom");

        attributes.add(SKINTYPEFACE);
    }

    public SkinAttribute(Typeface typeface) {
        this.typeface = typeface;
    }

    /**
     * 筛选View
     *
     * @param view
     * @param attrs
     */
    public void load(View view, AttributeSet attrs) {
        List<SkinPair> skinPairs = new ArrayList<>();
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            //获取属性名
            String attributeName = attrs.getAttributeName(i);
            //判断属性是否需要处理
            if (attributes.contains(attributeName)) {
                String attributeValue = attrs.getAttributeValue(i);
                //不处理写死的属性值
                if (attributeName.startsWith("#")) {
                    continue;
                }
                int resID;
                //以？开的的资源，定义在theme的attr属性中
                if (attributeValue.startsWith("?")) {
                    //主题中的属性ID
                    int attrID = Integer.parseInt(attributeValue.substring(1));
                    //实际的资源ID
                    resID = SkinThemeUtils.getResID(view.getContext(), new int[]{attrID})[0];
                } else {
                    resID = Integer.parseInt(attributeValue.substring(1));
                }

                //可被替换的属性
                if (resID != 0) {
                    SkinPair skinPair = new SkinPair(attributeName, resID);
                    skinPairs.add(skinPair);
                }
            }
        }

        //将view与之对应的可动态替换的属性放入集合
        //TextView都放入集合中，用于修改全局字体
        //SkinViewSupport接口的View都放入集合中
        if (!skinPairs.isEmpty() || view instanceof TextView || view instanceof SkinViewSupport) {
            SkinView skinView = new SkinView(view, skinPairs);
            skinView.applySkin(typeface);
            skinViews.add(skinView);
        }
    }

    /**
     * 换皮肤
     */
    public void applySkin() {
        for (SkinView skinView : skinViews) {
            skinView.applySkin(typeface);
        }
    }

    /**
     * 设置字体
     *
     * @param typeface
     */
    public void setTypeface(Typeface typeface) {
        this.typeface = typeface;
    }
}
